<?php
/**
 * Created by PhpStorm.
 * User: 姚荣
 * Date: 2017/5/27
 * Time: 17:57
 */
//----------------------------------
// 角色管理
//----------------------------------

namespace app\home\controller;

use app\common\controller\Base;
use app\common\model\Auth;
use app\common\model\Role as nRole;
use app\common\model\Admin;
use think\Validate;

class Role extends Base
{
    protected $role;
    protected $auth;
    protected $admin;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->role = new nRole();
        $this->auth = new Auth();
        $this->admin = new Admin();
    }

    public function index()
    {
        $this->veryauth();//验证权限
        return $this->fetch();
    }

    //获取角色列表，分页搜索
    public function rolelist()
    {
        $this->veryauth(1);//验证权限

        $pagenum = intval(input('get.pageNumber'));
        $pageSize = intval(input('get.pageSize'));
        $sortName = input('get.sortName');
        $sortOrder = input('get.sortOrder');

        $search = input('get.searchText');
        $where=[];
        if (!empty($search)) {
            $where['rolename'] = $search;
        }

        if ($pagenum == '' || $pagenum <= 0) {
            $pagenum = 1;
        }

        $retArray = [];

        $sortwhere = $sortName . ' ' . $sortOrder;


        $sortwhere = $sortName == '' ? ' id asc ' : $sortwhere;

        $roleTotal = $this->role->where($where)->count();

        $roleInfo = $this->role->order($sortwhere)->where($where)->page($pagenum, $pageSize)->select();

        //dump($role->getLastSql());

        $retArray['total'] = intval($roleTotal);
        $retArray['rows'] = $roleInfo;

        return json($retArray);
    }

    //权限列表
    /*
     * id = -1 新增  id = 角色id 编辑
     * */
    public function authlist()
    {
        $id = input('post.id');

        $topauthlist = $this->auth->order('id asc')->where('level=1')->select();
        if ($id == -1) {
            foreach ($topauthlist as $key => $v) {
                $where = ['level' => 2, 'pid' => $v['id']];
                $towauthlist = $this->auth->order('id asc')->where($where)->select();
                $autharray = "<li><label for='ser" . $v['id'] . "'><input id='ser" . $v['id'] . "' type='checkbox' value='" . $v['id'] . "' name='auth'/>" . $v['name'] . "</label>&nbsp;</li><li>";
                foreach ($towauthlist as $key => $v1) {
                    $autharray .= "<label for='ser" . $v1['id'] . "'><input id='ser" . $v1['id'] . "' type='checkbox' value='" . $v1['id'] . "' name='auth'/>" . $v1['name'] . "</label>&nbsp;";
                }
                $autharray .= "</li>";
                $allauth[] = $autharray;
            }
        } else {
            $roleauth = $this->role->find($id);

            $roleautharray = explode(',', $roleauth['authlist']);

            foreach ($topauthlist as $key => $v) {
                $count = 0;
                $where = ['level' => 2, 'pid' => $v['id']];
                $towauthlist = $this->auth->order('id asc')->where($where)->select();
                for ($i = 0; $i < count($roleautharray); $i++) {
                    if ($roleautharray[$i] == $v['id']) {
                        $autharray = "<li><label><input type='checkbox' checked value='" . $v['id'] . "' name='auth'/>" . $v['name'] . "</label></li><li>";
                        $count = 1;
                        break;
                    }
                }

                if ($count == 0) {
                    $autharray = "<li><label><input type='checkbox' value='" . $v['id'] . "' name='auth'/>" . $v['name'] . "</label></li><li>";
                }

                foreach ($towauthlist as $key => $v1) {
                    $count = 0;
                    for ($j = 0; $j < count($roleautharray); $j++) {
                        if ($roleautharray[$j] == $v1['id']) {
                            $autharray .= "<label><input type='checkbox' checked value='" . $v1['id'] . "' name='auth'/>" . $v1['name'] . "</label>";
                            $count = 2;
                            break;
                        }
                    }

                    if ($count == 0 || $count == 1) {
                        $autharray .= "<label><input type='checkbox' value='" . $v1['id'] . "' name='auth'/>" . $v1['name'] . "</label>";
                    }
                }
                $autharray .= "</li>";
                $allauth[] = $autharray;
            }

        }
        $auth = implode('', $allauth);
        return json($auth);

    }


//删除选中角色
    public function delrole()
    {
        $this->veryauth(1);//验证权限

        $mid = input('post.id');
        if (empty($mid)) {
            $retArray = ['rel' => 0, 'msg' => '参数不能为空'];
            return json($retArray);
        }


        $adminroleid = $this->admin->field('roleid')->select();//查询所有管理员的角色id
        $allroleid = array_column($adminroleid, 'roleid');//将二维数组，转化为一维数组

        $midarray = explode(',', $mid);//将字符串分割为数组

        $resarray = array_intersect($allroleid, $midarray);//获取两个数组的交集

        if (!empty($resarray)) {
            $rid = implode(',', $resarray);//将交集数组拼接为字符串
            $where1['id'] = ['in', $rid];
            $rolenamelist = $this->role->field('rolename')->where($where1)->select();//按id查询角色名
            $rolename = implode(',', array_column($rolenamelist, 'rolename'));//拼接为字符串

            $retArray = ['rel' => 0, 'msg' => $rolename . '角色下存在管理员，无法删除'];
            return json($retArray);
        }

        $where['id'] = ['in', "$mid"];

        $delmem = $this->role->where($where)->delete();

        if ($delmem) {
            $retArray = ['rel' => 1, 'msg' => '删除成功'];
        } else {
            $retArray = ['rel' => 0, 'msg' => '删除失败'];
        }

        return json($retArray);
    }

    //ajax增加角色
    public function add()
    {
        $this->veryauth(1);//验证权限
        $rolearray = input('post.');

        // 数据验证
        $validate = new Validate([
                'rolename' => 'require',
                'authlist' => 'require'
            ]
            ,
            $msg = [
                'rolename' => '名称必须填写',
                'authlist' => '至少选择一项权限'
            ]);

        if (!$validate->check($rolearray)) {
            $ajaxresult = ['rel' => 0, 'msg' => $validate->getError()];
            return json($ajaxresult);
        }

        $rolearray['authlist'] = rtrim($rolearray['authlist'], ',');
        $rolearray['showall'] = 1;
        $mwhere = ['rolename' => $rolearray['rolename']];
        $roleif = $this->role->where($mwhere)->find();
        if ($roleif) {
            $ajaxresult = ['rel' => 0, 'msg' => '角色已存在'];
            return json($ajaxresult);
        }

        $upinfo = $this->role->allowField(true)->isUpdate(false)->save($rolearray);
        if ($upinfo) {
            $ajaxresult = ['rel' => 1, 'msg' => '添加成功'];
        } else {
            $ajaxresult = ['rel' => 0, 'msg' => '添加失败'];
        }

        return json($ajaxresult);
    }

    //ajax修改角色
    public function editerrole()
    {
        $this->veryauth(1);//验证权限
        $rolearray = input('post.');
        // 数据验证
        $validate = new Validate([
                'id' => 'require|number',
                'rolename' => 'require',
                'authlist' => 'require'
            ]
            ,
            $msg = [
                'id' => 'id不正确',
                'rolename' => '名称必须填写',
                'authlist' => '至少选择一项权限'
            ]);

        if (!$validate->check($rolearray)) {
            $ajaxresult = ['rel' => 0, 'msg' => $validate->getError()];
            return json($ajaxresult);
        }
        $rolearray['authlist'] = rtrim($rolearray['authlist'], ',');
        $mwhere = ['rolename' => $rolearray['rolename']];
        $mwhere['id'] = ['neq', $rolearray['id']];
        $roleif = $this->role->where($mwhere)->find();
        if ($roleif) {
            $ajaxresult = ['rel' => 0, 'msg' => '角色已存在'];
            return json($ajaxresult);
        }
        $where = ['id' => $rolearray['id']];
        $verimem = $this->role->find($where);

        if ($verimem) {
            $upinfo = $this->role->allowField(true)->isUpdate(true)->save($rolearray);
            if ($upinfo) {
                $ajaxresult = ['rel' => 1, 'msg' => '修改成功'];
            } else {
                $ajaxresult = ['rel' => 0, 'msg' => '修改失败或信息没有改变'];
            }
        } else {
            $ajaxresult = ['rel' => 0, 'msg' => '角色不存在'];
        }

        return json($ajaxresult);
    }


}
